package com.jielin.handling.controller.login;

import com.alibaba.fastjson.JSONObject;
import com.jielin.handling.Annotation.MyPower;
import com.jielin.handling.bean.AppResult;
import com.jielin.handling.entity.material.MaterialFile;
import com.jielin.handling.entity.police.PoliceMan;
import com.jielin.handling.entity.unit.Organization;
import com.jielin.handling.entity.vo.PersonRecordVo;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.redis.RedisKey;
import com.jielin.handling.redis.RedisTemplateX;
import com.jielin.handling.service.accesspath.AccessPathService;
import com.jielin.handling.service.material.MaterialFileService;
import com.jielin.handling.service.police.PoliceManService;
import com.jielin.handling.service.unit.UnitService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 类名称：LoginController 创建人：zhanglongdeng@163.com 创建时间：2019年3月15日 下午3:17:55
 * 类描述：登录
 */
@RestController
@RequestMapping("/")
@Slf4j
@CrossOrigin
@Validated
public class LoginController {
    @Autowired
    private PoliceManService policeManService;
    @Autowired
    private RedisTemplateX redisTemplateX;
    @Autowired
    private AccessPathService accessPathService;
    @Autowired
    private UnitService unitService;
    @Autowired
    private MaterialFileService materialFileService;
    @Autowired
    private XskyService xskyService;
    //

    /**
     * 用户_登录
     *
     * @param
     * @return
     */
    @PostMapping(value = "/login", produces = "application/json")
    public AppResult login(@RequestBody PoliceMan policeMan, HttpServletRequest request) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("用户登录请求user===>{}", JSONObject.toJSONString(policeMan));
        // user = userService.login(user);
        policeMan = policeManService.login(policeMan);
        if (policeMan != null) {
            String policeId = policeMan.getId();
            policeManService.updateLoginDate(policeId, request.getRemoteAddr());// 更新登录时间与ip
            // 生成token并放入缓存(存储时间以秒为单位)
            String token = StringUtil.generatorUUID();
            List<String> powerList = accessPathService.findAllPowerPathByPoliceId(policeId);
            if (powerList == null || powerList.size() == 0) {
                result.setData(data);
                result.setMsg("没有权限！");
                result.setCode(-8);
                return result;
            }
            List<String> accessList = new ArrayList<String>();
            Iterator<String> iterator = powerList.iterator();
            while (iterator.hasNext()) {// 使用iterator进行元素删除，如果并发操作，需要对Iterator对象加锁。
                String item = iterator.next();
                if (!item.contains("/")) {
                    accessList.add(item);
                    iterator.remove();
                }
            }
            redisTemplateX.set(token, policeId, ConstantUtil.USER_TOKEN_EXPIRE);
            redisTemplateX.set(token + RedisKey.POWER_LIST, powerList, ConstantUtil.USER_TOKEN_EXPIRE);
            data.put("token", token);
            data.put("userId", policeId);
            data.put("policeCode", policeMan.getPoliceCode());
            data.put("unitId", policeMan.getOrganizationid());
            data.put("accessList", accessList);
            Organization unitInfo = unitService.findUnitInfoById(policeMan.getOrganizationid());
            String unitCode = unitInfo != null ? unitInfo.getHandleUnitCode() : "没有单位信息！";

            //查询当前单位下授权码是否过期
//            Map<String,Object>map = unitService.findRegistrationCode(unitCode);
//            if(map.size()>1){
//                //未过期
//                data.put("isOverTime", "0");
//            }else{
//                //已过期
//                data.put("isOverTime", "1");
//            }
            data.put("unitCode", unitCode);
            redisTemplateX.set(policeId, unitCode, ConstantUtil.USER_TOKEN_EXPIRE);
            result.setData(data);
            result.setMsg("登录成功");
            result.setCode(200);
        } else {
            result.setData(data);
            result.setMsg("用户名密码错误");
            result.setCode(-1);
        }
        return result;
    }

    /**
     * 用户_退出
     *
     * @param "userId"
     * @return
     */
    @RequestMapping(value = "/logout")
    public AppResult logout(String token) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("注销......");
        redisTemplateX.del(token);
        redisTemplateX.del(token + RedisKey.POWER_LIST);
        data.put("提示", "退出成功！");
        result.setData(data);
        result.setMsg("退出成功！");
        result.setCode(200);
        return result;
    }

    /**
     * 民警头像拍照17b84
     */
//    @MyPower(name = "民警头像拍照", url = "/savePhoto", isPublic = true)
//    @RequestMapping("savePhoto")
//    public AppResult savePhoto(MultipartFile file, String id, String fileString) {
//        AppResult appResult = new AppResult();
//        JSONObject date = new JSONObject();
//        log.info("file:{}", JSONObject.toJSONString(file));
//        log.info("id:{}", JSONObject.toJSONString(id));
//        log.info("fileString:{}", JSONObject.toJSONString(fileString));
//        if (ConstantUtil.XSKYRESTORAGE) {
//            if (policeManService.savePhoto(id, fileString) > 0) {
//                return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("文件上传成功！");
//            } else {
//                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("文件上传失败！(可能原因：1.上传文件为空)");
//            }
//
//
//        } else {
//            // 文件夹地址
//            String folderPath = ConstantUtil.PHOTO_PATH + "police" + File.separator + "headpic" + File.separator;
//            // 获取当前时间毫秒数拼接
//            String trueFileName = String.valueOf(System.currentTimeMillis());
//            // 生成文件夹
//            File folderFile = new File(folderPath);
//            if (!folderFile.exists()) {
//                folderFile.mkdirs();
//            }
//            try {
//                if (file != null) {
//                    // 文件原名称
//                    String fileName = file.getOriginalFilename();
//                    // 截取文件后缀
//                    String fileType = fileName.substring(fileName.lastIndexOf("."));
//                    // 拼接存储文件路径
//                    String path = folderPath + trueFileName + fileType;// 磁盘存储路径
//                    String filePath = File.separator + "police" + File.separator + "headpic" + File.separator + trueFileName
//                            + fileType;// 数据库存储
//                    FileOutputStream out = new FileOutputStream(path);
//                    out.write(file.getBytes());
//                    out.flush();
//                    out.close();
//                    // 设置图片路径
//                    int value = policeManService.savePhoto(filePath, id);
//                    // 返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
//                    String returnPath = ConstantUtil.SERVER_URL + filePath;
//                    if (value > 0) {
//                        date.put("value", 1);
//                        date.put("returnPath", returnPath);
//                        appResult.setCode(200);
//                        appResult.setMsg("添加民警头像成功!");
//                        appResult.setData(date);
//                    } else {
//                        date.put("value", 1);
//                        appResult.setCode(200);
//                        appResult.setMsg("添加民警头像失败!");
//                        appResult.setData(date);
//
//                    }
//                    return appResult;
//                } else if (fileString != null && fileString != "") {//// 解码Base64上传图片
//                    // String
//                    // truefileType=fileString.substring(fileString.indexOf("/")+1,fileString.indexOf(";"));//
//                    // 获取图片类型
//                    System.out.println("base图片字符串》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》" + fileString);
//                    String fileType = ".png";
//                    String path = folderPath + trueFileName + fileType;
//
//                    // Base64解码
//                    BASE64Decoder decoder = new BASE64Decoder();
//                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
//                    log.info("Base64解码后:\n" + base64String);
//                    byte[] b = decoder.decodeBuffer(base64String);
//                    for (int i = 0; i < b.length; ++i) {
//                        if (b[i] < 0) {// 调整异常数据
//                            b[i] += 256;
//                        }
//                    }
//                    String filePath = File.separator + "police" + File.separator + "headpic" + File.separator + trueFileName
//                            + fileType;// 数据库存储
//
//                    FileOutputStream out = new FileOutputStream(path);
//                    out.write(b);
//                    out.flush();
//                    out.close();
//
//                    // 设置图片路径
//                    int value = policeManService.savePhoto(filePath, id);
//                    // 返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
//                    String returnPath = ConstantUtil.SERVER_URL + filePath;
//                    if (value > 0) {
//                        date.put("value", 1);
//                        date.put("returnPath", returnPath);
//                        appResult.setCode(200);
//                        appResult.setMsg("添加民警头像成功!");
//                        appResult.setData(date);
//                    } else {
//                        date.put("value", 0);
//                        appResult.setCode(-1);
//                        appResult.setMsg("添加民警头像失败!");
//                        appResult.setData(date);
//                    }
//                    return appResult;
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            appResult.setCode(-1);
//            appResult.setMsg("添加民警头像失败!");
//        }
//        return appResult;
//    }

    //查询个人案件信息
    @MyPower(name = "查询个人案件信息", url = "/queryStatistical", isPublic = true)
    @RequestMapping("queryStatistical")
    public AppResult queryStatistical(@RequestBody JSONObject Param) {
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();

        //未完结
        int InHand = policeManService.queryInHand(Param);
        //已完结
        int ToAudit = policeManService.queryToAudit(Param);
        //笔录模板数量
        int BiLu = policeManService.queryBiLu(Param);
        data.put("InHand", InHand);
        data.put("ToAudit", ToAudit);
        data.put("BiLu", BiLu);
        return AppResult.builder().setCode(200).setMsg("查询个人案件信息成功!").setData(data);
    }


    /**
     * 查询本月办理案件信息
     *
     * @param policeId 警员id
     * @return
     */
    @MyPower(name = "查询本月办理案件信息", url = "/selectPersonThisMonthCaseInfo", isPublic = true)
    @RequestMapping("/selectPersonThisMonthCaseInfo")
    public AppResult selectPersonThisMonthCaseInfo(@NotNull(message = "传入的policeId为null，请传值")
                                                   @NotEmpty(message = "传入的policeId空字符串，请传值") String policeId) {
        JSONObject data = new JSONObject();
        data.put("value", policeManService
                .selectPersonThisMonthCaseInfo(policeId));
        return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("查询本月办理案件信息成功!").setData(data);
    }

    @MyPower(name = "查询个人本月的卷宗上传信息", url = "/findPersonalAudit", isPublic = true)
    @RequestMapping(value = "/findPersonalAudit")
    public AppResult findPersonalAudit(String policeId) {
        PersonRecordVo recordVo = new PersonRecordVo();
        //查询当前登录的民警本月的上传卷宗总记录数
        List<MaterialFile> list = materialFileService.findPersonalAudit(policeId);
        recordVo.setTotal(list.size());
        //对查询出来的记录数再进行一个文件类型的区分及判断
        for (MaterialFile materialFile : list) {
            //视频文件格式的检测并记录下该类文件的数量
            if (materialFile.getFiletype().matches("(.swf|.flv|.mp4|.rmvb|.avi|.mpeg|.ram|.mov|.wmv)$")) {
                int video = recordVo.getVideo();
                video++;
                recordVo.setVideo(video);
            }
            //图片文件格式校验并进行数量统计
            else if (materialFile.getFiletype().matches(".(jpg|bmp|gif|ico|jpeg|tif|png|raw|tga)$")
            ) {
                int picture = recordVo.getPicture();
                picture++;
                recordVo.setPicture(picture);
            }
            //音频文件检测并进行数量统计
            else if (materialFile.getFiletype().matches(".(mp3|wav|midi|wma|vqf)$")) {
                int audio = recordVo.getAudio();
                audio++;
                recordVo.setAudio(audio);

            }
            //其他文件格式的记录数
            recordVo.setOther(list.size() - recordVo.getAudio() - recordVo.getPicture() - recordVo.getVideo());
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("value", recordVo);
        return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("查询个人本月的卷宗上传信息成功！").setData(jsonObject);
    }

    @MyPower(name = "民警头像拍照", url = "/savePhoto", isPublic = true)
    @RequestMapping("/savePhoto")
    public AppResult savePhoto2(MultipartFile file, String id,String fileString) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();

        log.info("添加民镜头像");
        if (ConstantUtil.XSKYRESTORAGE) {
            if (file == null&&fileString==null) {
                date.put("data", "没有相关的文件");
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("添加警告！").setData(date);
            }
            if (policeManService.savePhoto2(file, id, fileString) > 0) {

                return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("文件上传成功！");
            } else {
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("文件上传失败！(可能原因：1.上传文件为空)");
            }
        }
        else {
            log.info("file:{}", JSONObject.toJSONString(file));
            log.info("id:{}", JSONObject.toJSONString(id));
            log.info("fileString:{}", JSONObject.toJSONString(fileString));
            String folderPath = ConstantUtil.PHOTO_PATH + "police" + File.separator + "headpic" + File.separator;
            // 获取当前时间毫秒数拼接
            String trueFileName = String.valueOf(System.currentTimeMillis());
            // 生成文件夹
            File folderFile = new File(folderPath);
            if (!folderFile.exists()) {
                folderFile.mkdirs();
            }
            try {
                if (file != null) {
                    // 文件原名称
                    String fileName = file.getOriginalFilename();
                    // 截取文件后缀
                    String fileType = fileName.substring(fileName.lastIndexOf("."));
                    // 拼接存储文件路径
                    String path = folderPath + trueFileName + fileType;// 磁盘存储路径
                    String filePath = File.separator + "police" + File.separator + "headpic" + File.separator + trueFileName
                            + fileType;// 数据库存储
                    FileOutputStream out = new FileOutputStream(path);
                    out.write(file.getBytes());
                    out.flush();
                    out.close();
                    // 设置图片路径
                    int value = policeManService.savePhoto(filePath, id);
                    // 返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    if (value > 0) {
                        date.put("value", 1);
                        date.put("returnPath", returnPath);
                        appResult.setCode(200);
                        appResult.setMsg("添加民警头像成功!");
                        appResult.setData(date);
                    } else {
                        date.put("value", 1);
                        appResult.setCode(200);
                        appResult.setMsg("添加民警头像失败!");
                        appResult.setData(date);

                    }
                    return appResult;
                } else if (fileString != null && fileString != "") {//// 解码Base64上传图片
                    // String
                    // truefileType=fileString.substring(fileString.indexOf("/")+1,fileString.indexOf(";"));//
                    // 获取图片类型
                    System.out.println("base图片字符串》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》" + fileString);
                    String fileType = ".png";
                    String path = folderPath + trueFileName + fileType;

                    // Base64解码
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
                    byte[] b = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {// 调整异常数据
                            b[i] += 256;
                        }
                    }
                    String filePath = File.separator + "police" + File.separator + "headpic" + File.separator + trueFileName
                            + fileType;// 数据库存储

                    FileOutputStream out = new FileOutputStream(path);
                    out.write(b);
                    out.flush();
                    out.close();

                    // 设置图片路径
                    int value = policeManService.savePhoto(filePath, id);
                    // 返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    if (value > 0) {
                        date.put("value", 1);
                        date.put("returnPath", returnPath);
                        appResult.setCode(200);
                        appResult.setMsg("添加民警头像成功!");
                        appResult.setData(date);
                    } else {
                        date.put("value", 0);
                        appResult.setCode(-1);
                        appResult.setMsg("添加民警头像失败!");
                        appResult.setData(date);
                    }
                    return appResult;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            appResult.setCode(-1);
            appResult.setMsg("添加民警头像失败!");
            return appResult;
        }
    }
}

